package com.glsc.ngateway.oaflow.service;

import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;

@Component
public class OaLoginService {

    Logger logger = LoggerFactory.getLogger(OaLoginService.class);

    //wkhtmltopdf在系统中的路径
    private static final String toPdfToolWindows = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf";
    private static final String toPdfToolLinux = "/usr/local/bin/wkhtmltopdf";


    @Value("${oalogin.host}")
    public String host;
    @Value("${oalogin.destPath}")
    public String destPath;

    public ResponseEntity<byte[]> getFileStream(File file, HttpServletRequest request) throws Exception {

        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<byte[]> entity = null;
        InputStream in = null;
        in = new FileInputStream(file);
        byte[] bytes = new byte[in.available()];

        String[] patharray = file.getAbsolutePath().split("/");
        String filename = patharray[patharray.length - 1];
        String imageName = filename;
        //处理IE下载文件的中文名称乱码的问题
        String header = request.getHeader("User-Agent").toUpperCase();
        if (header.contains("MSIE") || header.contains("TRIDENT") || header.contains("EDGE")) {
            imageName = URLEncoder.encode(imageName, "utf-8");
            imageName = imageName.replace("+", "%20"); //IE下载文件名空格变+号问题
        } else {
            imageName = new String(imageName.getBytes(), "iso-8859-1");
        }
        in.read(bytes);
        headers.add("Content-Disposition", "attachment;filename=" + imageName);
        entity = new ResponseEntity<byte[]>(bytes, headers, HttpStatus.OK);
        return entity;
    }


    public File createFileFromHtml(String srcPath, String sessionId) {

        try {
            String fileName = UUID.randomUUID() + ".pdf";
            File file = new File(destPath + fileName);
            File parent = file.getParentFile();
            //如果pdf保存路径不存在，则创建路径
            if (!parent.exists()) {
                parent.mkdirs();
            }
            StringBuilder cmd = new StringBuilder();
            if (System.getProperty("os.name").toLowerCase().contains("win")) {
                logger.info("服务器为windows");
                cmd.append(toPdfToolWindows);
            } else {
                logger.info("服务器为linux");
                cmd.append(toPdfToolLinux);
            }

            cmd.append(" ");
            cmd.append(" --cookie JSESSIONID ");
            cmd.append(sessionId);
            cmd.append(" ");
            cmd.append(" --cookie ecology_JSessionid ");
            cmd.append(sessionId);
            cmd.append(" ");
            cmd.append(host + srcPath);
            cmd.append("  ");
            cmd.append(file.getAbsolutePath());
            logger.info("htmlToPdf,执行命令:" + cmd.toString());

            try {
                Process proc = Runtime.getRuntime().exec(cmd.toString());
                HtmlToPdfInterceptor error = new HtmlToPdfInterceptor(proc.getErrorStream());
                HtmlToPdfInterceptor output = new HtmlToPdfInterceptor(proc.getInputStream());
                error.start();
                output.start();
                proc.waitFor();
                logger.info("HTML2PDF成功，" + srcPath + "----" + destPath);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                logger.error("HTML2PDF失败，" + srcPath + "----" + destPath, e);
                return null;
            } catch (Exception e) {
                logger.error("HTML2PDF失败，" + srcPath + "----" + destPath, e);
                return null;
            }
            File createFile = new File(destPath + fileName);
            return createFile;
        } catch (Exception e) {
            logger.error("HTML2PDF失败，" + srcPath + "----" + destPath, e);
            return null;
        }
    }

    @Slf4j
    private static class HtmlToPdfInterceptor extends Thread {
        private InputStream is;

        public HtmlToPdfInterceptor(InputStream is) {
            this.is = is;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is, "utf-8");
                BufferedReader br = new BufferedReader(isr);
                String line;
                while ((line = br.readLine()) != null) {
                    System.out.println(line); //输出内容
                }
            } catch (IOException e) {
                log.error("异常", e);
            }
        }
    }
}
